<template>
  <div class="post-card" :class="cardClass" @click="handleCardClick">
    <!-- 帖子头部 -->
    <div class="post-header">
      <!-- 用户信息 -->
      <div class="post-user">
        <img
          v-if="post.user?.avatar"
          :src="post.user.avatar"
          :alt="post.user.username"
          class="user-avatar"
        />
        <div v-else class="avatar-placeholder">
          {{ post.user?.username ? post.user.username.charAt(0).toUpperCase() : 'U' }}
        </div>
        <div class="user-info">
          <span class="username">{{ post.user?.username || '匿名用户' }}</span>
          <span class="post-time">{{ post.createdAt ? formatRelativeTime(post.createdAt) : '' }}</span>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div v-if="showActions" class="post-actions">
        <button
          v-if="canEdit"
          class="action-btn action-edit"
          @click.stop="handleEdit"
          title="编辑"
        >
          <el-icon><Edit /></el-icon>
        </button>
        <button
          v-if="canDelete"
          class="action-btn action-delete"
          @click.stop="handleDelete"
          title="删除"
        >
          <el-icon><Delete /></el-icon>
        </button>
        <button
          v-if="canPin"
          :class="['action-btn', `action-pin${post.pinned ? ' active' : ''}`]"
          @click.stop="handlePin"
          :title="post.pinned ? '取消置顶' : '置顶'"
        >
          <el-icon><Top /></el-icon>
        </button>
        <button
          v-if="canLock"
          :class="['action-btn', `action-lock${post.locked ? ' active' : ''}`]"
          @click.stop="handleLock"
          :title="post.locked ? '解锁' : '锁定'"
        >
          <el-icon><Lock /></el-icon>
        </button>
        <button
          class="action-btn action-more"
          @click.stop="handleMore"
          title="更多"
        >
          <el-icon><More /></el-icon>
        </button>
      </div>
    </div>
    
    <!-- 帖子内容 -->
    <div class="post-content">
      <!-- 分类标签 -->
      <div v-if="post.category" class="post-category">
        <el-tag :type="getCategoryType()" size="small">{{ post.category.name }}</el-tag>
      </div>
      
      <!-- 帖子标题 -->
      <h3 class="post-title">
        <span v-if="post.pinned" class="pin-tag">置顶</span>
        <span v-if="post.recommended" class="recommend-tag">推荐</span>
        {{ post.title }}
      </h3>
      
      <!-- 帖子摘要 -->
      <div v-if="showSummary && post.content" class="post-summary">
        {{ getSummary() }}
        <span v-if="needReadMore" class="read-more">... 查看更多</span>
      </div>
      
      <!-- 自定义内容 -->
      <div v-if="$slots.content" class="post-custom-content">
        <slot name="content" :post="post" />
      </div>
    </div>
    
    <!-- 帖子图片 -->
    <div v-if="showImages && post.images && post.images.length > 0" class="post-images">
      <img
        v-for="(image, index) in displayImages"
        :key="index"
        :src="image"
        :alt="`帖子图片 ${index + 1}`"
        class="post-image"
        @click.stop="handleImageClick(image, index)"
      />
      <div v-if="post.images.length > maxImages" class="image-more">
        +{{ post.images.length - maxImages }}
      </div>
    </div>
    
    <!-- 帖子统计 -->
    <div v-if="showStats" class="post-stats">
      <div class="stat-item">
        <el-icon class="stat-icon"><Message /></el-icon>
        <span class="stat-text">{{ post.commentCount || 0 }} 评论</span>
      </div>
      <div class="stat-item">
        <el-icon class="stat-icon"><Star /></el-icon>
        <span class="stat-text">{{ post.likeCount || 0 }} 点赞</span>
      </div>
      <div class="stat-item">
        <el-icon class="stat-icon"><View /></el-icon>
        <span class="stat-text">{{ post.viewCount || 0 }} 浏览</span>
      </div>
      <div v-if="post.shareCount" class="stat-item">
        <el-icon class="stat-icon"><Share /></el-icon>
        <span class="stat-text">{{ post.shareCount }} 分享</span>
      </div>
    </div>
    
    <!-- 底部操作 -->
    <div v-if="showBottomActions" class="post-bottom-actions">
      <button
        :class="['action-btn', `action-like${isLiked ? ' active' : ''}`]"
        @click.stop="handleLike"
      >
        <el-icon><Star /></el-icon>
        <span>{{ isLiked ? '已赞' : '点赞' }}</span>
      </button>
      <button class="action-btn action-comment" @click.stop="handleComment">
        <el-icon><Message /></el-icon>
        <span>评论</span>
      </button>
      <button class="action-btn action-share" @click.stop="handleShare">
        <el-icon><Share /></el-icon>
        <span>分享</span>
      </button>
      <button
        :class="['action-btn', `action-collect${isCollected ? ' active' : ''}`]"
        @click.stop="handleCollect"
      >
        <el-icon><Star /></el-icon>
        <span>{{ isCollected ? '已收藏' : '收藏' }}</span>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, withDefaults, defineProps, defineEmits, defineExpose } from 'vue'
import { useRouter } from 'vue-router'
import { ElTag, ElIcon } from 'element-plus'
import { Edit, Delete, Top, Lock, More, Message, Star, View, Share } from '@element-plus/icons-vue'
import type { Post } from '../types/forum'
import { formatRelativeTime, truncateString as truncateText } from '../utils/common'

// Props
interface ExtendedPost extends Omit<Post, 'viewCount' | 'likeCount' | 'commentCount'> {
  category?: {
    id: number
    name: string
  }
  user?: {
    id: number
    username: string
    avatar?: string
    email?: string
  }
  pinned?: boolean
  recommended?: boolean
  locked?: boolean
  images?: string[]
  shareCount?: number
  commentCount?: number
  likeCount?: number
  viewCount?: number
}

interface Props {
  post: ExtendedPost
  currentUserId?: string | number
  isAdmin?: boolean
  isModerator?: boolean
  isLiked?: boolean
  isCollected?: boolean
  showImages?: boolean
  showStats?: boolean
  showSummary?: boolean
  showActions?: boolean
  showBottomActions?: boolean
  maxImages?: number
  summaryLength?: number
  size?: 'small' | 'medium' | 'large'
  clickable?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  post: () => ({
    id: 0,
    title: '',
    content: '',
    categoryId: 0,
    userId: 0,
    username: '',
    viewCount: 0,
    likeCount: 0,
    commentCount: 0,
    status: 'APPROVED' as const,
    createdAt: '',
    updatedAt: ''
  }),
  isAdmin: false,
  isModerator: false,
  isLiked: false,
  isCollected: false,
  showImages: true,
  showStats: true,
  showSummary: true,
  showActions: true,
  showBottomActions: true,
  maxImages: 3,
  summaryLength: 150,
  size: 'medium',
  clickable: true
})

// Router
const router = useRouter()

// Emits
const emit = defineEmits<{
  'click': [post: Post]
  'edit': [post: Post]
  'delete': [post: Post]
  'pin': [post: Post]
  'lock': [post: Post]
  'like': [post: Post]
  'unlike': [post: Post]
  'collect': [post: Post]
  'uncollect': [post: Post]
  'comment': [post: Post]
  'share': [post: Post]
  'image-click': [image: string, index: number, images: string[]]
  'more': [post: Post]
}>()

// Refs
const internalIsLiked = ref(props.isLiked)
const internalIsCollected = ref(props.isCollected)

// 计算属性
const cardClass = computed(() => {
  return [
    `post-card-${props.size}`,
    {
      'post-card-pinned': props.post.pinned,
      'post-card-recommended': props.post.recommended,
      'post-card-locked': props.post.locked,
      'post-card-clickable': props.clickable
    }
  ]
})

const displayImages = computed(() => {
  return props.post.images ? props.post.images.slice(0, props.maxImages) : []
})

const needReadMore = computed(() => {
  if (!props.post.content) return false
  return props.post.content.length > props.summaryLength
})

const canEdit = computed(() => {
  return props.isAdmin || 
         props.isModerator || 
         (props.post.user?.id && props.currentUserId === props.post.user.id)
})

const canDelete = computed(() => {
  return props.isAdmin || 
         props.isModerator || 
         (props.post.user?.id && props.currentUserId === props.post.user.id)
})

const canPin = computed(() => {
  return props.isAdmin || props.isModerator
})

const canLock = computed(() => {
  return props.isAdmin || props.isModerator
})

// 获取分类标签类型
const getCategoryType = (): "primary" | "success" | "warning" | "info" | "danger" => {
  const typeMap: Record<string, "primary" | "success" | "warning" | "info" | "danger"> = {
    '技术': 'primary',
    '分享': 'success',
    '求助': 'warning',
    '公告': 'info'
  }
  return typeMap[props.post.category?.name as string] || 'info'
}

// 获取帖子摘要
const getSummary = () => {
  if (!props.post.content) return ''
  return truncateText(props.post.content, props.summaryLength)
}

// 将ExtendedPost转换为Post类型
const convertToPost = (extendedPost: ExtendedPost): Post => {
  return {
    id: extendedPost.id,
    title: extendedPost.title,
    content: extendedPost.content,
    categoryId: extendedPost.categoryId,
    categoryName: extendedPost.categoryName,
    userId: extendedPost.userId,
    username: extendedPost.username,
    avatar: extendedPost.avatar,
    viewCount: extendedPost.viewCount || 0,
    likeCount: extendedPost.likeCount || 0,
    commentCount: extendedPost.commentCount || 0,
    tags: extendedPost.tags,
    status: extendedPost.status,
    isTop: extendedPost.isTop,
    isHot: extendedPost.isHot,
    isLiked: extendedPost.isLiked,
    isFollowed: extendedPost.isFollowed,
    isCollected: extendedPost.isCollected,
    summary: extendedPost.summary,
    author: extendedPost.author,
    category: extendedPost.category,
    createdAt: extendedPost.createdAt,
    updatedAt: extendedPost.updatedAt,
    comments: extendedPost.comments
  }
}

// 事件处理
const handleCardClick = () => {
  if (props.clickable && props.post.id) {
    // 跳转到帖子详情页
    router.push(`/forum/post/${props.post.id}`)
    emit('click', convertToPost(props.post))
  }
}

const handleEdit = () => {
  emit('edit', convertToPost(props.post))
}

const handleDelete = () => {
  emit('delete', convertToPost(props.post))
}

const handlePin = () => {
  emit('pin', convertToPost(props.post))
}

const handleLock = () => {
  emit('lock', convertToPost(props.post))
}

const handleLike = () => {
  if (internalIsLiked.value) {
    emit('unlike', convertToPost(props.post))
  } else {
    emit('like', convertToPost(props.post))
  }
  internalIsLiked.value = !internalIsLiked.value
}

const handleComment = () => {
  emit('comment', convertToPost(props.post))
}

const handleShare = () => {
  emit('share', convertToPost(props.post))
}

const handleCollect = () => {
  if (internalIsCollected.value) {
    emit('uncollect', convertToPost(props.post))
  } else {
    emit('collect', convertToPost(props.post))
  }
  internalIsCollected.value = !internalIsCollected.value
}

const handleImageClick = (image: string, index: number) => {
  emit('image-click', image, index, props.post.images || [])
}

const handleMore = () => {
  emit('more', convertToPost(props.post))
}

// 暴露方法
defineExpose({
  toggleLike: handleLike,
  openEdit: handleEdit,
  triggerDelete: handleDelete
})
</script>

<style scoped>
.post-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: default;
}

/* 尺寸样式 */
.post-card-small {
  padding: 12px;
}

.post-card-medium {
  padding: 16px;
}

.post-card-large {
  padding: 20px;
}

/* 点击样式 */
.post-card-clickable {
  cursor: pointer;
}

.post-card-clickable:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

/* 置顶和推荐样式 */
.post-card-pinned {
  border-left: 4px solid #409eff;
}

.post-card-recommended {
  border-left: 4px solid #67c23a;
}

.post-card-locked {
  opacity: 0.8;
}

/* 帖子头部 */
.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.post-user {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.post-time {
  font-size: 12px;
  color: #909399;
}

/* 操作按钮 */
.post-actions {
  display: flex;
  gap: 4px;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  padding: 0;
  border: none;
  border-radius: 4px;
  background-color: transparent;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background-color: #f0f2f5;
  color: #606266;
}

.action-btn.active {
  color: #409eff;
}

.action-edit:hover {
  color: #409eff;
}

.action-delete:hover {
  color: #f56c6c;
}

.action-pin:hover,
.action-pin.active {
  color: #e6a23c;
}

.action-lock:hover,
.action-lock.active {
  color: #f56c6c;
}

/* 帖子内容 */
.post-content {
  margin-bottom: 12px;
}

.post-category {
  margin-bottom: 8px;
}

.post-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: flex;
  align-items: center;
  gap: 8px;
}

.pin-tag {
  color: #e6a23c;
  font-size: 12px;
  font-weight: normal;
}

.recommend-tag {
  color: #67c23a;
  font-size: 12px;
  font-weight: normal;
}

.post-summary {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.read-more {
  color: #409eff;
  cursor: pointer;
}

.post-custom-content {
  margin-bottom: 8px;
}

/* 帖子图片 */
.post-images {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.post-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  transition: all 0.3s ease;
}

.post-image:hover {
  transform: scale(1.05);
}

.image-more {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
}

.post-card-large .post-image,
.post-card-large .image-more {
  width: 100px;
  height: 100px;
}

.post-card-small .post-image,
.post-card-small .image-more {
  width: 60px;
  height: 60px;
}

/* 帖子统计 */
.post-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  font-size: 14px;
}

/* 底部操作 */
.post-bottom-actions {
  display: flex;
  gap: 16px;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
}

.post-bottom-actions .action-btn {
  width: auto;
  padding: 4px 12px;
  gap: 4px;
  color: #606266;
}

.post-bottom-actions .action-btn:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.post-bottom-actions .action-btn.active {
  color: #f56c6c;
}

.post-bottom-actions .action-btn.active:hover {
  background-color: #fef0f0;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .post-card {
    margin-bottom: 12px;
  }
  
  .post-card-small {
    padding: 10px;
  }
  
  .post-card-medium {
    padding: 14px;
  }
  
  .post-card-large {
    padding: 18px;
  }
  
  .post-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .post-actions {
    align-self: flex-end;
  }
  
  .post-title {
    font-size: 15px;
  }
  
  .post-summary {
    font-size: 13px;
  }
  
  .post-stats {
    gap: 12px;
  }
  
  .post-bottom-actions {
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .post-images {
    flex-wrap: wrap;
  }
  
  .post-stats {
    flex-wrap: wrap;
  }
  
  .post-bottom-actions {
    justify-content: space-between;
  }
}
</style>